// index.js
Page({
  data: {
    globalData: getApp().globalData,
    keyword: '',
    carFlag: true,
    count: 1,
    banners: [],
    commend: [],
    products: [],
    product: {},  //要加购的商品
  },

  onLoad() {
    this.getBanners()
    this.getCommend()
    this.getProducts()
  },

  select() {
    wx.navigateTo({
      url: '/pages/classifyList/classifyList?keyword=' + this.data.keyword,
    })
  },
  getBanners() {
    let that = this
    wx.request({
      url: that.data.globalData.server + '/banner/query',
      method: 'GET',
      data: {
        bannerStatus: true,
        pageNum: 1,
        pageSize: 10
      },
      success(res) {
        that.setData({banners: res.data.data.records})
      }
    })
  },
  getCommend() {
    let that = this
    wx.request({
      url: that.data.globalData.server + '/product/query',
      method: 'GET',
      data: {
        sales: 1, 
        status: 1,
        pageNum: 1,
        pageSize: 3
      },
      success(res) {
        that.setData({commend: res.data.data.records})
      }
    })
  },
  getProducts() {
    let that = this
    wx.request({
      url: that.data.globalData.server + '/product/query',
      method: 'GET',
      data: {
        status: 1,
        pageNum: 1,
        pageSize: 4
      },
      success(res) {
        that.setData({products: res.data.data.records})
      }
    })
  },
  plus() {
    this.setData({count: this.data.count + 1})
  },
  minus() {
    if(this.data.count > 1) this.setData({count: this.data.count - 1})
  },
  showCar(e) {
    this.setData({carFlag: false, product: e.currentTarget.dataset.item, count: 1})
  },
  hideCar() {
    this.setData({carFlag: true})
  },
  joincar() {
    if(wx.getStorageSync('user') == '') {
      wx.showModal({
        title: '提示',
        content: '请登录后购买',
        complete: (res) => {
          if (res.confirm) {
            wx.navigateTo({url: '/pages/login/login',})
          } else if (res.cancel) {
            return
          }
        }
      })
    } else {
      let that = this
      wx.request({
        url: that.data.globalData.server + '/cart',
        method: 'POST',
        data: {
          userId: wx.getStorageSync('user').userId,
          productId: this.data.product.productId,
          count: this.data.count
        },
        success(res) {
          that.hideCar()
          wx.showToast({
            title: '加购成功',
          })
        },
      })
    }
  },
  toProduct(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({url: '/pages/productDetail/productDetail?id=' + id})
  },
})
